<?
/**************************************************************************************************
 Name: VPS Web Save Order
 System: VPS
 Sub-system: Vendor Components
 Description: Script to initiate a transaction with the VPS
 Version: 1.1
 Date: 10/09/2002
 History:  Version 1.1 - PHP release
 History:  Version 1.0 - ASP release
*************************************************************************************************/

// *** Include the initialisation files
include ("init-includes.php");


// Set some variables
$TargetURL = $PurchaseURL;													// Specified in init-includes.php
$VerifyServer = $Verify;														// Specified in init-includes.php

/**************************************************************************************************
	Retrieve order information from your database
**************************************************************************************************/

	/*
	Example code for connecting to a MySQL database
	*/

	// Make the connection
	$db = mysql_connect($myHost, $myUser, $myPass);

	// Select the database
	mysql_select_db($myDB,$db);

	// 
	$sql = "SELECT * from $myTable
		WHERE VendorTxCode='" . $_POST["VendorTxCode"] . "'
	";

	// Get the query object
	@$result=mysql_query($sql,$db);
	
	// Get the row
	$row=mysql_fetch_array($result);


// Set order description
// If there's an alternate description, use it (truncated to 100 characters) otherwise use default
if ($_POST['Description'] != ''){
	$Description = substr($_POST['Description'],0,100);
} else {
	$Description = $DefaultDescription;								//  Specified in init-protx.php
}

/**************************************************************************************************
	Set all the required outgoing properties for the initial HTTPS post to the VPS
**************************************************************************************************/

// Create an array of values to send
$data = array (
		'VPSProtocol' => $ProtocolVersion, 							// Protocol version (specified in init-includes.php)
		'TxType' => $row['TxType'],											// Transaction type
		'Vendor' => $Vendor,														// Vendor name (specified in init-protx.php)
		'VendorTxCode' => $row['VendorTxCode'],					// Unique transaction code (generated by vendor)
		'Amount' => $row['Amount'],											// Value of order (supplied by vendor)
		'Currency' => $DefaultCurrency,									// Currency of order (default specified in init-protx.php)
		'Description' => $Description,									// Description of order 
	);


// Check if client number is supplied
if(trim($_POST['ClientNumber']) != ''){
	// If so, add client number to data array to be appended to POST
	$data['ClientNumber'] = $_POST['ClientNumber'];
}

// Add card holder name
$data['CardHolder'] = $_POST['CardHolder'];
// Add card number
$data['CardNumber'] = $_POST['CardNumber'];

// Check if start date is supplied
if($_POST['StartDateMonth']){
	// If so, add start date to data array to be appended to POST
	$data['StartDate'] = $_POST['StartDateMonth'] . $_POST['StartDateYear'];
}

// Add expiry date
$data['ExpiryDate'] = $_POST['ExpiryDateMonth'] . $_POST['ExpiryDateYear'];

// Check if issue number is supplied
if(trim($_POST['IssueNumber']) != ''){
	// If so, add issue number to data array to be appended to POST
	$data['IssueNumber'] = $_POST['IssueNumber'];
}
// Check if CV2 data is supplied
if(trim($_POST['CV2']) != ''){
	// If so, add CV2 data to data array to be appended to POST
	$data['CV2'] = $_POST['CV2'];
}

// Add card type
$data['CardType'] = $_POST['CardType'];

// Check if address and/or postcode are supplied
if($row['Address']){
	// If so, add address (truncated to 200 characters) to data array to be appended to POST
	$data["Address"] = substr($row['Address'],0,200);
}
if($row['PostCode']){
	// If so, add postcode (truncated to 10 characters) to data array to be appended to POST
	$data["PostCode"] = substr($row['PostCode'],0,10);
}


// Format values as url-encoded key=value pairs
$data = formatData($data);

/**************************************************************************************************
	Send the post to the target URL
		if anything goes wrong with the connection process:
			- $response["Status"] will be 'FAIL';
			- $response["StatusDetail"] will be set to describe the problem;
**************************************************************************************************/
$response = requestPost($TargetURL, $data);

/**************************************************************************************************
	Check the Status and act appropriately
'*************************************************************************************************/

// Get the first word of the status -- in case it has appended values (eg. REPEATED)
$baseStatus = array_shift(split(" ",$response["Status"]));

switch($baseStatus) {

	case 'OK':
		/**************************************************************************************************
			Transaction registered successfully, so store the pertinient info
			i.e. the VPSTxID and SecurityCode in your database here
		**************************************************************************************************/

			/*
				You must store the VPSTxID and the SecurityKey, returned from the VPS, against
				your own unique transaction id for this purchase, in your database.
				These will be needed later to identify the transaction the VPS is notifying you about,
				and for any refunds you may wish to make against this purchase in the future.

				The VPSTxID and Security Key are returned in $response["VPSTxId"] and $response["SecurityKey"] respectively.
			*/

			// Demo code for updating a mySQL database

				// Set the query (update existing record)
				$sql = "UPDATE $myTable
					SET 
						Status = '" . $response["Status"] . "',
						StatusDetail = '" . $response["StatusDetail"] . "',
						VPSTxId = '" . $response["VPSTxID"] . "',
						SecurityKey = '" . $response["SecurityKey"] . "',
						TxAuthNo = '" . $response["TxAuthNo"] . "'
					WHERE id = " . $_POST["id"]
				;

				// Get the query as an associative array
				@$result=mysql_query($sql,$db);

		/**************************************************************************************************
			Now redirect the user to your success URL
		**************************************************************************************************/
		header("Location: " . $DefaultCompletionURL . "?VendorTxCode=" . $row['VendorTxCode']);

		break; // END case 'OK'

	case 'NOTAUTHED':
		/**************************************************************************************************
			Transaction was not authorised
			Redirect the user to your not authorised URL
		**************************************************************************************************/
		header("Location: " . $DefaultNotAuthedURL);

		break; // END case 'NOTAUTHED'

	// Connection timed out
	case 'FAIL':
		/**************************************************************************************************
			Connection to protx could not be made (timed out)
		**************************************************************************************************/

			/*
				The status was not OK, so you may wish to update a status field your database to reflect this.
				This could enable you to delete orders that did not complete at a later date.
			*/

		echo ("
			<HTML>
			<BODY>
			Connection to protx server failed.<BR><BR>
			Status=" . $response['Status'] . "<BR>
			StatusDetail=" . $response['StatusDetail'] . "<BR>
			</BODY>
			</HTML>
		");

		break; // END case 'FAIL'

	// There was an error of some kind
	default:
		/**************************************************************************************************
			Status was not OK, so whilst communication was successful, something was wrong with the POST
			Display information about the error on screen and update your database with this information
		**************************************************************************************************/

			/*
				The status was not OK, so you may wish to update a status field your database to reflect this.
				This could enable you to delete orders that did not complete at a later date.
			*/

		echo ("
			<HTML>
			<BODY>
			Communication with the PROTX Server was successful but transaction was not registered.  See details below:<BR><BR>
			Status=" . $response['Status'] . "<BR>
			StatusDetail=" . $response['StatusDetail'] . "<BR>
			Protocol=" . $response['VPSProtocol'] . "<BR>
		");

		if (isset($response['VPSTxId'])){
			echo("
				VPSTxId=" . $response['VPSTxId'] . "<BR>
				SecurityKey=" . $response['SecurityKey'] . "<BR>
				NextURL=" . $response['NextURL'] . "
			");
		}

		echo("
			</BODY>
			</HTML>
		");

		break; // END default

} // END switch($bastStatus)

// Close the database	connection
mysql_close($db);

?>